package com.yskj.mwk.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class QRCodeGenerator {

    /**
     * 生成二维码图片字节流
     * @param content   文本内容
     * @return  PNG格式的字节数组
     */
    public String generateQRCode(String content) {
        int width=600;
        int height=600;
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错率
        hints.put(EncodeHintType.MARGIN, 1); // 二维码边距
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    content,
                    BarcodeFormat.QR_CODE,
                    width,
                    height,
                    hints
            );

            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            String fileName = UUID.randomUUID().toString() + ".png";
            //3.1 判断文件夹是否存在，不存在则创建
            String imageDirPath = "./upload/QR";
            File imageDir = new File(imageDirPath);
            if (!imageDir.exists()) {
                imageDir.mkdirs();
            }

            //3.2 拼接文件完整路径
            String imageFilePath = imageDirPath + "/" + fileName;
            ImageIO.write(image, "PNG", new File(imageFilePath));
            return imageFilePath;
        }catch (Exception e){
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
        qrCodeGenerator.generateQRCode("201526541112");
    }
}
